package com.wh.springbootshiro.controller;

import com.wh.springbootshiro.pojo.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * @Auther: HuiEr
 * @Date: 2020/3/3 17:48
 * @Description
 */
@Controller
public class UserController {
    private Logger logger= LoggerFactory.getLogger(UserController.class);

    @RequestMapping("toLogin")
    public String toLogin(){
        return "login";
    }

    @RequestMapping("toIndex")
    public String toIndex(){
        return "index";
    }

    @RequestMapping("login")
    public String login(User user, Model model,boolean remember){
        UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getPassword());
        token.setRememberMe(remember);
        Subject subject = SecurityUtils.getSubject();
        try{
            subject.login(token);
        }catch (UnknownAccountException err){
            logger.info("用户名不正确");
            model.addAttribute("usernameError","用户名不正确");
            return "login";
        }catch (IncorrectCredentialsException err){
            logger.info("密码不正确");
            model.addAttribute("passwordError","密码不正确");
            return "login";
        }catch (Exception err){
            logger.info("其他错误"+err.fillInStackTrace());
            model.addAttribute("otherError","其他错误");
            return "login";
        }
       /* User user1=(User)subject.getPrincipal();
        model.addAttribute("user",user1);*/
        return "index";
    }

    @RequestMapping("addUser")
    public String addUser(){
        return "addUser";
    }

    @RequestMapping("toUnauthorization")
    public String toUnauthorization(){
        return "unauthorization";
    }

    @RequestMapping("delete")
    @RequiresPermissions("user:delete")
    public String toDelete(){
        return "delete";
    }
}
